/*
 * @Author: lyuan2018
 * @Date: 2019-08-08 11:14:56
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-07-30 10:41:42
 * 账户管理Store
 */
import { observable, action } from 'mobx';
import { WeaForm, WeaTableNew } from 'comsMobx';
import { message, Modal } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import { ValidateForm } from './util';
import * as Api from '../../apis/setting/mailAccount';

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  fields: [],
  accountNewVisible: false,
  editVisible: false,
  editStep: 1,
  editId: '',
  editResult: {},
  validateLoading: false,
  editLoading: true,
  newStep: 0,
  newFirstFileds: [],
  newSecondFileds: [],
  mailType: '',
  isNewInit: true,
  nextLoading: false,
  autoGetFolderLoading: false,
  chooseFolders: [],
  chooseFolderName: '',
};
export default class AccountStore {
  @observable accountTable = new TableStore(); // 账户列表
  @observable accountForm = new WeaForm(); // 编辑账户表单
  @observable newFirstForm = new WeaForm();
  @observable newSecondForm = new WeaForm();
  @observable fields = initalState.fields; // 编辑账户表单数据
  @observable accountNewVisible = initalState.accountNewVisible; // 新建账户显隐
  @observable editVisible = initalState.editVisible;
  @observable editStep = initalState.editStep; // 编辑账户操作步数记录
  @observable editId = initalState.editId; // 编辑账户ID
  @observable editResult = initalState.editResult; // 账户校验信息结果
  @observable validateLoading = initalState.validateLoading;
  @observable editLoading = initalState.editLoading;

  @observable mailType = initalState.mailType; // 邮件服务器类型记录

  @observable newStep = initalState.newStep; // 新建执行步数
  @observable newFirstFileds = initalState.newFirstFileds; // 第一步存放数据
  @observable newSecondFileds = initalState.newSecondFileds; // 第二步存放数据
  @observable isNewInit = initalState.isNewInit; // 标志是否新建初始化
  @observable nextLoading = initalState.nextLoading; // 新建账户'下一步'按钮 loading 控制

  accoutOpt;

  @observable autoGetFolderLoading = initalState.autoGetFolderLoading;
  @observable chooseFolders = initalState.chooseFolders;
  @observable chooseFolderName = initalState.chooseFolderName;

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action clear = () => this.setStoreState(initalState);

  // 账户列表请求
  @action getMailAccount = (params, initPage = false) => {
    Api.getMailAccount(params).then(
      action('fetchSuccess', (res) => {
        initPage ? this.accountTable.getDatas(res.sessionkey) : this.accountTable.getDatas(res.sessionkey, 1);
      }),
    );
  }

  // 账户删除操作
  @action deleteUserMailAccount = (params) => {
    message.loading(`${getLabel('19611', '处理中')}...`, 0);
    Api.deleteUserMailAccount(params).then((res) => {
      message.destroy();
      if (res.flag) {
        message.success(getLabel(83472, '删除成功！'), 2);
        this.getMailAccount();
        if (this.accoutOpt && typeof this.accoutOpt === 'function') this.accoutOpt();
      } else {
        // message.destroy();
        message.error(res.message || getLabel(384401, '删除失败，请重试！'), 2);
      }
    });
  }

  // 设置默认账户
  @action updateUserDefaultMailAccount = (params) => {
    Api.updateUserDefaultMailAccount(params).then(
      action('fetchSuccess', (res) => {
        if (res.flag) {
          this.getMailAccount('', true);
        }
      }),
    );
  }


  // 邮件账户开启发票识别
  @action openIdentifyInvoiceMailAccount = (params) => {
    Api.openIdentifyInvoiceMailAccount(params).then((res) => {
      if (res.flag) {
        this.getMailAccount('', true);
      }
    });
  }

  /** ******************************************* EditAccount ******************************************** */
  // 账户编辑Condition请求
  @action getEmailAccountCondition = (params, callback) => {
    this.editLoading = true;
    Api.getEmailAccountCondition(params).then((res) => {
      this.accountForm = new WeaForm();
      this.accountForm.initFormFields(res.conditioninfo);
      this.fields = res.conditioninfo;
      this.editLoading = false;
      if (callback) callback();
    });
  }

  // 账户编辑获取数据信息
  @action getMailAccountBean = (params, callback) => {
    Api.getMailAccountBean(params).then((res) => {
      let formParams = this.accountForm.getFormParams();
      for (let attr in formParams) {
        if (Object.prototype.hasOwnProperty.call(res.emailAccountBean, attr)) {
          if (attr === 'sentItems') {
            let setItemsVal = res.emailAccountBean[attr] ? [{ id: res.emailAccountBean[attr], name: res.emailAccountBean[attr], validate: true }] : [];
            this.accountForm.updateFields({ [attr]: { value: setItemsVal } });
          } else {
            this.accountForm.updateFields({ [attr]: { value: res.emailAccountBean[attr] } });
          }
        }
      }
      if (callback) callback();
    });
  }

  @action editSubmit = () => {
    let formParams = this.accountForm.getFormParams();
    let serverType = formParams.serverType;
    window.e9HideFormFieldKeys = []; // 表单校验忽略值
    if (serverType !== '3') {
      window.e9HideFormFieldKeys = ['ews_service_url', 'ews_domain', 'ews_version'];
    } else {
      window.e9HideFormFieldKeys = ['popServer', 'popServerPort', 'smtpServer', 'smtpServerPort'];
    }
    if (serverType !== '2' || (serverType === '2' && formParams.isReceiveSent !== '1')) {
      window.e9HideFormFieldKeys = [...window.e9HideFormFieldKeys, 'sentItems'];
    }
    ValidateForm(this.accountForm, () => {
      this.mailType = formParams.serverType;
      this.editStep += 1;
      let params = { ...formParams, operation: 'update', id: this.editId };
      if (serverType !== '2' || (serverType === '2' && formParams.isReceiveSent !== '1')) {
        params = { ...params, sentItems: '' };
      }
      if (serverType === '1') {
        params = { ...params, isReceiveSent: '0' };
      }
      if (params.sentItems) {
        params.sentItems = params.sentItems[0] && params.sentItems[0].name || '';
      }
      if (this.editStep * 1 === 2) {
        this.validateLoading = true;
        Api.makeUserMailAccount(params).then((res) => {
          if (res.response.status === 200) {
            if (!res.flag && (res.errorType && res.errorType == 'port')) {
              Modal.confirm({
                title: getLabel(131329, '信息确认'),
                content: res.msg,
              });
              this.editStep -= 1;
              this.validateLoading = false;
              return;
            }

            if (res.status * 1 === 1) {
              this.editResult = res;
              this.validateLoading = false;
              if (res.mailState) {
                this.getMailAccount();
                if (this.accoutOpt && typeof this.accoutOpt === 'function') this.accoutOpt();
              }
            }
          } else {
            this.validateLoading = false;
            this.editResult = null;
          }
        }).catch(() => {
          // msg: "/api/email/setting/makeUserMailAccount fetch 数据处理异常: [object Object]"
          // responseCode: 504
          // statusText: "Gateway Time-out"
          this.validateLoading = false;
          this.editResult = null;
        });
      }
    });
  }

  /** ******************************************* NewAccount ******************************************** */
  @action getNewAccountCondition = (callback) => {
    Api.getEmailAddAccountCondition().then(
      action('fetchSuccess', (res) => {
        this.newFirstForm = new WeaForm();
        this.newFirstForm.initFormFields(res.conditioninfo);
        this.newFirstFileds = res.conditioninfo;
        if (callback) callback();
      }),
    );
    if (callback) callback();
  }

  @action stepChange = (params, callback) => {
    if (this.newStep * 1 === 0) {
      ValidateForm(this.newFirstForm, () => {
        let accountMailAddress = this.newFirstForm.getFormParams().accountMailAddress;
        if (this.isNewInit) {
          this.nextLoading = true;
          Api.getEmailEditAccountCondition(params).then(
            action('fetchSuccess', (res) => {
              this.newSecondForm.initFormFields(res.conditioninfo);
              this.newSecondFileds = res.conditioninfo;
              Api.getMailAccountDefaultInfo({ accountMailAddress }).then((result) => {
                let formParams = this.newSecondForm.getFormParams();
                for (let attr in formParams) {
                  if (Object.prototype.hasOwnProperty.call(result.emailAccountBean, attr)) {
                    if (attr === 'sentItems') {
                      let setItemsVal = result.emailAccountBean[attr] ? [{ id: result.emailAccountBean[attr], name: result.emailAccountBean[attr], validate: true }] : [];
                      this.newSecondForm.updateFields({ [attr]: { value: setItemsVal } });
                    } else {
                      this.newSecondForm.updateFields({ [attr]: { value: result.emailAccountBean[attr] } });
                    }
                  }
                }
                this.nextLoading = false;
              });
            }),
          );
        }
        this.newStep += 1;
      });
    } else if (this.newStep * 1 === 1) {
      let firstFormParams = this.newFirstForm.getFormParams();
      let formParams = this.newSecondForm.getFormParams();
      let serverType = formParams.serverType;
      window.e9HideFormFieldKeys = [];// 表单校验忽略值
      if (serverType !== '3') {
        window.e9HideFormFieldKeys = ['ews_service_url', 'ews_domain', 'ews_version'];
      } else {
        window.e9HideFormFieldKeys = ['popServer', 'popServerPort', 'smtpServer', 'smtpServerPort'];
      }
      if (serverType !== '2' || (serverType === '2' && formParams.isReceiveSent !== '1')) {
        window.e9HideFormFieldKeys = [...window.e9HideFormFieldKeys, 'sentItems'];
      }
      ValidateForm(this.newSecondForm, () => {
        this.newStep += 1;
        this.nextLoading = true;
        this.validateLoading = true;
        this.mailType = formParams.serverType;
        let newparams = { ...firstFormParams, ...formParams, operation: 'add' };
        if (serverType !== '2' || (serverType === '2' && formParams.isReceiveSent !== '1')) {
          newparams = { ...newparams, sentItems: '' };
        }
        if (serverType === '1') {
          newparams = { ...newparams, isReceiveSent: '0' };
        }
        if (newparams.sentItems) {
          newparams.sentItems = newparams.sentItems[0] && newparams.sentItems[0].name || '';
        }
        Api.makeUserMailAccount(newparams).then(
          action('fetchSuccess', (res) => {
            if (res.response.status === 200) {
              if (!res.flag && (res.errorType && res.errorType == 'port')) {
                Modal.confirm({
                  title: getLabel(131329, '信息确认'),
                  content: res.msg,
                });
                this.newStep -= 1;
                this.validateLoading = false;
                this.nextLoading = false;
                return;
              }

              this.editResult = res;
              this.validateLoading = false;
              this.nextLoading = false;
              if (res.mailState) {
                if (this.accoutOpt && typeof this.accoutOpt === 'function') this.accoutOpt();
              }
              if (callback) callback(res.mailState);
            } else {
              this.validateLoading = false;
              this.nextLoading = false;
              this.editResult = null;
            }
          }),
        ).catch(() => {
          // msg: "/api/email/setting/makeUserMailAccount fetch 数据处理异常: [object Object]"
          // responseCode: 504
          // statusText: "Gateway Time-out"
          this.validateLoading = false;
          this.nextLoading = false;
          this.editResult = null;
        });
      });
    }
  }

  onGetFolderName = async (params) => {
    let result = await Api.getEmailsentFolderName(params);
    return result;
  }
}
